﻿using NewTest.Dao;
using NewTest.Demos;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace NewTest.Demos
{
    public class BaseMaker : IDemos
    {

        public void Init()
        {
            Console.WriteLine("启动BaseMaker.Init");
            Console.WriteLine("生成文件结构开始...");
            string BaseNname = "MyNet" + DateTime.Now.ToString("yyyyMMddHHmmss");
            Directory.CreateDirectory("C:/" + BaseNname);
            Directory.CreateDirectory("C:/" + BaseNname + "/Repositories");
            Directory.CreateDirectory("C:/" + BaseNname + "/Repositories/Repositorie");
            Directory.CreateDirectory("C:/" + BaseNname + "/Repositories/IRepositorie");
            Directory.CreateDirectory("C:/" + BaseNname + "/Services");
            Directory.CreateDirectory("C:/" + BaseNname + "/Services/Service");
            Directory.CreateDirectory("C:/" + BaseNname + "/Services/IService");
            Directory.CreateDirectory("C:/" + BaseNname + "/Models");
            Console.WriteLine("生成文件结构结束...");
            Console.WriteLine("===============================================");
            Console.WriteLine("遍历生成开始...");
            var db = SugarDao.GetInstance();
            var isLog = db.IsEnableLogEvent;
            db.IsEnableLogEvent = false;
            string sql = "select name from sysobjects where xtype in ('U','V') ";
            var tables = db.GetDataTable(sql);
            if (tables != null && tables.Rows.Count > 0)
            {
                foreach (DataRow dr in tables.Rows)
                {
                    string tableName = dr["name"].ToString();
                    var currentTable = db.GetDataTable(string.Format("select top 1 * from {0}", new ClassGenerating().GetTableNameWithSchema(db, tableName).GetTranslationSqlName()));

                    var tableColumns = new ClassGenerating().GetTableColumns(db, tableName);
                    string className = tableName;
                    var classCode = new ClassGenerating().DataTableToClass(currentTable, className + "Model", "Models", tableColumns);
                    Console.WriteLine("生成" + className + ".cs");
                    CreateFile("C:\\" + BaseNname + "\\Models\\" + className + ".cs", classCode, Encoding.UTF8);

                    Console.WriteLine("生成" + className + "Repositorie.cs");
                    CreateFile("C:\\" + BaseNname + "\\Repositories\\Repositorie\\" + className + "Repositorie.cs", RepositoryTemplate.Replace("menu", className + "Model"), Encoding.UTF8);
                    Console.WriteLine("生成I" + className + "Repositorie.cs");
                    CreateFile("C:\\" + BaseNname + "\\Repositories\\IRepositorie\\I" + className + "Repositorie.cs", IRepositoryTemplate.Replace("menu", className + "Model"), Encoding.UTF8);

                    Console.WriteLine("生成" + className + "Service.cs");
                    CreateFile("C:\\" + BaseNname + "\\Services\\Service\\" + className + "Service.cs", ServiceTemplate.Replace("menu", className + "Model"), Encoding.UTF8);
                    Console.WriteLine("生成I" + className + "Service.cs");
                    CreateFile("C:\\" + BaseNname + "\\Services\\IService\\I" + className + "Service.cs", IServiceTemplate.Replace("menu", className + "Model"), Encoding.UTF8);

                }
            }
            db.IsEnableLogEvent = isLog;
            Console.WriteLine("遍历生成结束...");
        }

        #region 文件操作
        /// <summary>
        /// 创建一个文件,并将字符串写入文件。
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        /// <param name="text">字符串数据</param>
        /// <param name="encoding">字符编码</param>
        public static void CreateFile(string filePath, string text, Encoding encoding)
        {
            try
            {
                //如果文件不存在则创建该文件
                if (!IsExistFile(filePath))
                {
                    //获取文件目录路径
                    string directoryPath = GetDirectoryFromFilePath(filePath);

                    //如果文件的目录不存在，则创建目录
                    CreateDirectory(directoryPath);

                    //创建文件
                    FileInfo file = new FileInfo(filePath);
                    using (FileStream stream = file.Create())
                    {
                        using (StreamWriter writer = new StreamWriter(stream, encoding))
                        {
                            //写入字符串     
                            writer.Write(text);

                            //输出
                            writer.Flush();
                        }
                    }
                }
            }
            catch
            {
            }
        }
        /// <summary>
        /// 检测指定文件是否存在,如果存在则返回true。
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static bool IsExistFile(string filePath)
        {
            return File.Exists(filePath);
        }
        /// <summary>
        /// 从文件绝对路径中获取目录路径
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        public static string GetDirectoryFromFilePath(string filePath)
        {
            //实例化文件
            FileInfo file = new FileInfo(filePath);

            //获取目录信息
            DirectoryInfo directory = file.Directory;

            //返回目录路径
            return directory.FullName;
        }
        /// <summary>
        /// 创建一个目录
        /// </summary>
        /// <param name="directoryPath">目录的绝对路径</param>
        public static void CreateDirectory(string directoryPath)
        {
            //如果目录不存在则创建该目录
            if (!IsExistDirectory(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
        }
        /// <summary>
        /// 检测指定目录是否存在
        /// </summary>
        /// <param name="directoryPath">目录的绝对路径</param>        
        public static bool IsExistDirectory(string directoryPath)
        {
            return Directory.Exists(directoryPath);
        }
        #endregion
        
        #region Repository类模版
        public string RepositoryTemplate =
@"using Models;
using MySqlSugar;
using Repositories.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Repositories.Repository
{
    public class menuRepository : ImenuRepository
    {
        protected readonly SqlSugarClient _db;
        public menuRepository()
        {
            _db = SugarDao.GetInstance();
        }

        #region 查询

        /// <summary>
        /// 查询单条根据主键
        /// </summary>
        public menu GetById(int? id)
        {
            var model = _db.Queryable<menu>().InSingle(id);
            return model;
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        public Queryable<menu> GetList()
        {
            return _db.Queryable<menu>();
        }

        /// <summary>
        /// 根据条件查询
        /// </summary>
        public Queryable<menu> GetList(Expression<Func<menu, bool>> where)
        {
            return _db.Queryable<menu>().Where(where);
        }

        /// <summary>
        /// 按页查询 OrderFields string 支持复杂【id desc,name asc】
        /// </summary>
        public Queryable<menu> GetPageList(Expression<Func<menu, bool>> where, int pageIndex, int pageSize, string OrderFields)
        {
            return _db.Queryable<menu>().Where(where).OrderBy(OrderFields).Skip((pageIndex - 1) * pageSize).Take(pageSize);
        }
#endregion

        #region 删除
        /// <summary>
        /// 根据主键删除
        /// </summary>
        public bool DeleteById(int id)
        {
            return _db.Delete<menu, int>(id);
        }

        /// <summary>
        /// 根据主键组批量删除
        /// </summary>
        public bool DeleteById(int[] ids)
        {
            return _db.Delete<menu, int>(ids);
        }

        /// <summary>
        /// 根据实体删除【一定要带主键！！！】
        /// </summary>
        public bool DeleteByModel(menu model)
        {
            return _db.Delete(model);
        }

        #endregion

        #region 新增
        /// <summary>
        /// 强制新增，不管主键
        /// </summary>
        public menu Insert(menu model)
        {
            return (menu)_db.Insert(model);
        }

        /// <summary>
        /// 批量插入 适合海量数据插入
        /// </summary>
        public bool InsertRange(List<menu> list)
        {
            return _db.SqlBulkCopy(list);
        }

        #endregion

        #region 修改
        /// <summary>
        /// 根据实体更新【主键一定要有！！！】
        /// </summary>
        public bool Update(menu model)
        {
            return _db.Update(model);
        }

        /// <summary>
        /// 10条以上批量更新
        /// </summary>
        public bool UpdateRange(List<menu> list)
        {
            return _db.SqlBulkReplace(list);
        }
        #endregion
    }
}

";
        #endregion

        #region IRepository类模板
        public string IRepositoryTemplate =
@"using Models;
using MySqlSugar;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace Repositories.IRepository
{
    public interface ImenuRepository
    {
        #region 查询

        /// <summary>
        /// 查询单条根据主键
        /// </summary>
        menu GetById(int? id);

        /// <summary>
        /// 查询所有
        /// </summary>
        Queryable<menu> GetList();

        /// <summary>
        /// 根据条件查询
        /// </summary>
        Queryable<menu> GetList(Expression<Func<menu, bool>> where);

        /// <summary>
        /// 按页查询
        /// </summary>
        Queryable<menu> GetPageList(Expression<Func<menu, bool>> where, int pageIndex, int pageSize, string OrderFields);
        #endregion

        #region 删除
        /// <summary>
        /// 根据主键删除
        /// </summary>
        bool DeleteById(int id);

        /// <summary>
        /// 根据主键组批量删除
        /// </summary>
        bool DeleteById(int[] ids);

        /// <summary>
        /// 根据实体删除【一定要带主键！！！】
        /// </summary>
        bool DeleteByModel(menu model);

        #endregion

        #region 新增
        /// <summary>
        /// 强制新增，不管主键
        /// </summary>
        menu Insert(menu model);

        /// <summary>
        /// 批量插入 适合海量数据插入
        /// </summary>
        bool InsertRange(List<menu> list);

        #endregion

        #region 修改
        /// <summary>
        /// 根据实体更新【主键一定要有！！！】
        /// </summary>
        bool Update(menu model);

        /// <summary>
        /// 10条以上批量更新
        /// </summary>
        bool UpdateRange(List<menu> list);
        #endregion
    }
}
";
        #endregion

        #region Service类模板

        public string ServiceTemplate =
            @"using System;
using System.Collections.Generic;
using System.Text;
using Models;
using Repositories;
using Application.IService;
using Repositories.IRepository;

namespace Application.Service
{
    public class menuService : ImenuService
    {

        private readonly ImenuRepository _repository;
        public menuService(ImenuRepository repository)
        {
            _repository = repository;
        }

        #region 查询

        /// <summary>
        /// 查询单条根据主键
        /// </summary>
        /// <returns></returns>
        public menu GetById(int? id)
        {
            return _repository.GetById(id);
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public Queryable<menu> GetList()
        {
            return _repository.GetList();
        }

        /// <summary>
        /// 根据条件查询
        /// </summary>
        /// <returns></returns>
        public Queryable<menu> GetList(Expression<Func<menu, bool>> where)
        {
            return _repository.GetList(where);
        }

        /// <summary>
        /// 按页查询
        /// </summary>
        public Queryable<menu> GetPageList(Expression<Func<menu, bool>> where, int pageIndex, int pageSize, string OrderFields)
        {
            return _repository.GetPageList(where, pageIndex, pageSize, OrderFields);
        }
        #endregion

        #region 删除
        /// <summary>
        /// 根据主键删除
        /// </summary>
        public bool DeleteById(int id)
        {
            return _repository.DeleteById(id);
        }

        /// <summary>
        /// 根据主键组批量删除
        /// </summary>
        public bool DeleteById(int[] ids)
        {
            return _repository.DeleteById(ids);
        }

        /// <summary>
        /// 根据实体删除【一定要带主键！！！】
        /// </summary>
        public bool DeleteByModel(menu model)
        {
            return _repository.DeleteByModel(model);
        }

        #endregion

        #region 新增
        /// <summary>
        /// 强制新增，不管主键
        /// </summary>
        public menu Insert(menu model)
        {
            return _repository.Insert(model);
        }

        /// <summary>
        /// 批量插入 适合海量数据插入
        /// </summary>
        public bool InsertRange(List<menu> list)
        {
            return _repository.InsertRange(list);
        }

        #endregion

        #region 修改
        /// <summary>
        /// 根据实体更新【主键一定要有！！！】
        /// </summary>
        public bool Update(menu model)
        {
            return _repository.Update(model);
        }

        /// <summary>
        /// 10条以上批量更新
        /// </summary>
        public bool UpdateRange(List<menu> list)
        {
            return _repository.UpdateRange(list);
        }
        #endregion
    }
}
";
        #endregion

        #region IService类模板

        public string IServiceTemplate =
            @"using Models;
using System;
using System.Collections.Generic;
using System.Text;

namespace Application.IService
{
   public interface ImenuService
    {
        #region 查询

        /// <summary>
        /// 查询单条根据主键
        /// </summary>
        menu GetById(int? id);

        /// <summary>
        /// 查询所有
        /// </summary>
        Queryable<menu> GetList();

        /// <summary>
        /// 根据条件查询
        /// </summary>
        Queryable<menu> GetList(Expression<Func<menu, bool>> where);

        /// <summary>
        /// 按页查询
        /// </summary>
        Queryable<menu> GetPageList(Expression<Func<menu, bool>> where, int pageIndex, int pageSize, string OrderFields);
        #endregion

        #region 删除
        /// <summary>
        /// 根据主键删除
        /// </summary>
        bool DeleteById(int id);

        /// <summary>
        /// 根据主键组批量删除
        /// </summary>
        bool DeleteById(int[] ids);

        /// <summary>
        /// 根据实体删除【一定要带主键！！！】
        /// </summary>
        bool DeleteByModel(menu model);

        #endregion

        #region 新增
        /// <summary>
        /// 强制新增，不管主键
        /// </summary>
        menu Insert(menu model);

        /// <summary>
        /// 批量插入 适合海量数据插入
        /// </summary>
        bool InsertRange(List<menu> list);

        #endregion

        #region 修改
        /// <summary>
        /// 根据实体更新【主键一定要有！！！】
        /// </summary>
        bool Update(menu model);

        /// <summary>
        /// 10条以上批量更新
        /// </summary>
        bool UpdateRange(List<menu> list);
        #endregion
    }
}
"; 
        #endregion
    }
}
